# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from datetime import datetime
from odoo.exceptions import ValidationError, Warning


class RejectWizard(models.TransientModel):
    """
    使用单位变更审核不通过对话框
    """
    _name = 'tyibs.base.reject.wizard'
    content = fields.Text(required=True)

    @api.multi
    def reject(self,values):
        """
        审核不通过
        """
        self.ensure_one()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        self.env[res_model].browse(res_id).origin_write({'state': 'reject',
            'log_ids': [(0, False, {
                'res_model': res_model,
                'res_id': res_id,
                'user_id': self.env.uid,
                'content': u"审核不通过，原因：%s" % self.content,
                'time': datetime.utcnow()
            })]
        })

class ResUsersCreateBaseWizard(models.TransientModel):
    _name = "tyibs.base.res.users.create.base.wizard"

    login = fields.Char(string=u"登录账号", required=True, size=20)
    password = fields.Char(string=u"登录密码", required=True, size=20)
    confirm_password = fields.Char(string=u"确认密码", required=True, size=20)

    def check_user_exist(self):
        if self.password != self.confirm_password:
            raise ValidationError(u"两次输入的密码不一致。")
        user = self.env["res.users"].sudo().search([('login', '=', self.login)], limit=1)
        if user:
            raise Warning(u"登录账号已存在，请更改登录账号。")


class MaintenanceEmployeeUserCreateWizard(models.TransientModel):
    """
    维保单位创建员工关联的用户
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.maintenance.employee.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        employee_id = self.env[res_model].browse(res_id)
        res_user_id = self.env["res.users"].sudo().create({
            'user_type': 'main',
            'main_company_id': employee_id.enterprise_id.id,
            'login': self.login,
            'password': self.password,
            'name': employee_id.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_main_company_employee').id, False)]
        })
        employee_id.res_user_id = res_user_id


class MaintenanceCompanyUserCreateWizard(models.TransientModel):
    """
    创建维保单位管理员用户
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.maintenance.company.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        company = self.env[res_model].browse(res_id)
        user = self.env["res.users"].sudo().create({
            'user_type': 'main',
            'main_company_id': res_id,
            'login': self.login,
            'password': self.password,
            'name': company.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_main_company_manager').id, False)]
        })
        company.res_user_id = user


class DisposeCenterUserCreateWizard(models.TransientModel):
    """
    创建处置中心管理员用户
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.dispose.center.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        dispose_center = self.env[res_model].browse(res_id)
        user = self.env["res.users"].sudo().create({
            'user_type': 'service',
            'login': self.login,
            'password': self.password,
            'name': dispose_center.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_er_service_manager').id, False)]
        })
        dispose_center.res_user_id = user

class CustomerServiceUserCreateWizard(models.TransientModel):
    """
    创建处置中心坐席人员用户
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.customer.service.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        customer_service = self.env[res_model].browse(res_id)
        user = self.env["res.users"].sudo().create({
            'user_type': 'service',
            'login': self.login,
            'password': self.password,
            'name': customer_service.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_er_service_user').id, False)]
        })
        customer_service.res_user_id = user


class QsEmployeeUserCreateWizard(models.TransientModel):
    """
    创建质监人员用户
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.qs.employee.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        qs_employee = self.env[res_model].browse(res_id)
        group = "lift_base.group_lift_qs_area_manager"
        if qs_employee.enterprise_id.level == '1':
            group = "lift_base.group_lift_qs_city_manager"
        user = self.env["res.users"].sudo().create({
            'user_type': 'qs',
            'qs_company_id': qs_employee.enterprise_id.id,
            'login': self.login,
            'password': self.password,
            'name': qs_employee.name,
            'groups_id': [(4, self.env.ref(group).id, False)]
        })
        qs_employee.res_user_id = user


class UseCompanyUserCreateWizard(models.TransientModel):
    """
    创建使用单位用户(审批使用单位注册申请的时候)
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.use.company.user.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        order = self.env[res_model].browse(res_id)
        order.approve()
        user = self.env["res.users"].sudo().create({
            'user_type': 'use',
            'use_company_id': order.use_company_id.id,
            'login': self.login,
            'password': self.password,
            'name': order.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_use_company_user').id, False)]
        })
        order.write({
            'login': self.login,
            "password": self.password
        })
        if order.use_company_id.res_user_id:
            order.use_company_id.res_user_id.active = False
        order.use_company_id.res_user_id = user


class UseCompanyUserDirectlyCreateWizard(models.TransientModel):
    """
    创建使用单位用户(直接点击创建用户按钮)
    """
    _inherit = "tyibs.base.res.users.create.base.wizard"
    _name = 'tyibs.base.use.company.user.directly.create.wizard'

    @api.multi
    def create_res_user(self, values):
        """
        创建用户
        """
        self.ensure_one()
        self.check_user_exist()
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        use_company = self.env[res_model].browse(res_id)
        user = self.env["res.users"].sudo().create({
            'user_type': 'use',
            'use_company_id': res_id,
            'login': self.login,
            'password': self.password,
            'name': use_company.name,
            'groups_id': [(4, self.env.ref('lift_base.group_lift_use_company_user').id, False)]
        })
        use_company.res_user_id = user


class ResUsersEditPasswordWizard(models.TransientModel):
    """
    修改密码的wizard
    """
    _name = "tyibs.base.res.users.edit.pwd.wizard"

    password = fields.Char(string=u"登录密码", required=True, size=20)
    confirm_password = fields.Char(string=u"确认密码", required=True, size=20)

    @api.multi
    def edit_password(self, values):
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        employee = self.env[res_model].browse(res_id)
        if not employee.res_user_id:
            raise ValidationError(u"用户还没有创建，请联系系统管理员。")
        else:
            if self.password != self.confirm_password:
                raise ValidationError(u"两次输入的密码不一致。")
            employee.res_user_id.sudo().write({
                'password': self.password
            })


class LiftUseCompanyEditWizard(models.TransientModel):
    """
    变更使用单位
    """
    _name = 'tyibs.base.lift.use.company.edit.wizard'

    # 变更到这个使用单位
    use_company_id = fields.Many2one("tyibs.base.lift.use.company", required=True, string=u"使用单位")
    # 要变更使用单位的电梯
    lift_ids = fields.Many2many("tyibs.base.lift","tyibs_lift_use_company_edit_rel", "edit_id", "lift_id", string=u"电梯", required=True)

    @api.multi
    def start_bind(self,values):
        """
        绑定电梯
        """
        self.lift_ids.write({'use_company_id':self.use_company_id.id})
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'tyibs.base.lift',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'name':'本次变更使用单位的电梯',
            'domain':"[('id', 'in',%s)]" %([item.id for item in self.lift_ids]),
            'target': 'current',
        }

class ChooseLocationWizard(models.TransientModel):
    """
    地图选择位置
    """
    _name = 'tyibs.base.choose.location.wizard'

    ln = fields.Float(string=u"地点经度", digits=(32, 6), required=True)
    la = fields.Float(string=u"地点纬度", digits=(32, 6), required=True)

    @api.multi
    def save_location(self, values):
        """
        保存地址
        """
        res_model = values.get("active_model")
        res_id = values.get("active_id")
        record = self.env[res_model].browse(res_id)
        record.write({"ln": self.ln, "la": self.la})